﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Practices.Unity;
using SpLocalizer.Common;
using SpLocalizer.Common.Extensions;
using DbApi = SpLocalizer.Common.DbApi;

using Core.Threading.ThreadPools.TaskItems;
using Microsoft.Practices.EnterpriseLibrary.Logging;


namespace SpLocalizer.TranslationQueue
{
    /// <summary>
    /// Perform translation of single task
    /// </summary>
    public class TranslationTask : ITaskItem
    {

        private readonly BaseTranslationTask task;
        private readonly LogWriter _log;


        internal List<BaseTranslationTask> _IdenticalTasks = null;


        public TranslationTask(BaseTranslationTask task)
        {
            this.task = task;
            this._IdenticalTasks = task.LoadIdenticalTasksFromDatabase();
            this._log = ServiceContainer.Resolve<LogWriter>();
        }



        #region Implementation of ITaskItem

        /// <summary>
        /// Perform translation
        /// </summary>
        public void DoWork()
        {            
            ITranslationProvider TranslationProvider = ServiceContainer.Resolve<ITranslationProvider>();

            TranslationProvider.Translate(this.task);
            if (this.task.Status == TranslationTaskStatus.Translated)
            {
                this.task.PersistTranslation();
                if (this._IdenticalTasks != null)
                {
                    // If we have Identical tasks - persist translation for all of tham..
                    foreach (BaseTranslationTask identical in this._IdenticalTasks)
                    {
                        if (identical.SourceText.Equals(this.task.SourceText) &&
                            identical.FromLanguage.Equals(this.task.FromLanguage) &&
                            identical.ToLanguage.Equals(this.task.ToLanguage))
                        {
                            identical.TranslatedText = this.task.TranslatedText;
                            identical.Status = this.task.Status;
                            identical.PersistTranslation();
                        }

                    }
                }
            }
        }

        /// <summary>
        /// Save translation results into store
        /// </summary>
        /// <param name="task"></param>
        /// <param name="TranslationProvider"></param>
      /*  private void PersistTranslationResults(BaseTranslationTask task,  ITranslationProvider TranslationProvider)
        {

            this.task.PersistTranslation();

            _log.Write("Translation task {0} has been finished with {1} provider.".FormatWith(this.task.TaskId,
                    TranslationProvider.GetType().Name));

        }*/


        #endregion
    }
}
